package org.zdd.bookstore.crawl;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.ObjectUtils;
import org.zdd.bookstore.model.entity.BookInfo;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 爬虫类
 *
 * @author liqingbo
 */
public class BookParse {
    public static List<BookInfo> getData(HttpClient httpclient, String html, String category) throws ParseException, IOException {
        List<BookInfo> datas = new ArrayList<>();
        //解析网页（Jsoup返回Document就是浏览器的Document对象)
        Document doc = Jsoup.parse(html);
        //获取elements(元素) div[id=search_nature_rg]---> ul[class=bigimg]----> li  定位爬取数据位置
        Elements elements = doc.select("div[id=search_nature_rg]").select("ul[class=bigimg]").select("li");
        int i = 1;
        for (Element element : elements) {
            //图片url    attr方法确定属性
            String imgUrl = element.select("a[class=pic]").select("img").attr("data-original");
            //部分数据使用 img - src 属性
            if (ObjectUtils.isEmpty(imgUrl)) {
                imgUrl = element.select("a[class=pic]").select("img").attr("src");
            }
            //书名
            String bookName = element.select("a[class=pic]").select("img").attr("alt");
            //大纲
            String outline = element.select("p[class=name]").select("a").text();
            //描述
            String detail = element.select("p[class=detail]").text();
            //图书作者 元素
            Elements authorList = element.select("p[class=search_book_author]").select("span");
            //作者
            String author = authorList.get(0).select("a").attr("title");
            //出版日期
            String publishDate = authorList.get(1).text().substring(authorList.get(1).text().indexOf("/") + 1).trim();
            // 出版社
            String press = authorList.get(2).select("a").text();
            // 图书抢购价格
            String bookRobPrice = element.select("p[class=price]").select("span[class=search_now_price]").text().substring(1);
            // 图书定价
            String bookMarketPrice = element.select("p[class=price]").select("span[class=search_pre_price]").text().substring(1);
            //折扣
            String discount = element.select("p[class=price]").select("span[class=search_discount]").text();

            String bookSize = "";
            String bookPackage = "";
            String ISBN = "";
            String catalog = "";
            // 爬取商品详情页的信息  获取详细页面url
            // String bookInfoUrl ="http:" + element.select("a[class=pic]").attr("href");
            // //获得响应体数据
            // HttpResponse response = HttpUtil.getHtml(httpclient, bookInfoUrl);
            // //获取状态码
            // int statusCode = response.getStatusLine().getStatusCode();
            // if (statusCode == 200) {
            //     String entity = EntityUtils.toString(response.getEntity(), "utf-8");
            //     //图书详细页面
            //     Document bookInfoDoc = Jsoup.parse(entity);
            //     //定位到元素
            //     Elements bookDetailDesc = bookInfoDoc.select("div[t_box_left]");
            //     Elements keys = bookDetailDesc.select("ul[class=key clearfix]").select("li");
            //     //图书尺寸
            //     bookSize = keys.get(0).text();
            //     bookSize = bookSize.substring(bookSize.indexOf("：") + 1);
            //     // 图书包装
            //     bookPackage = keys.get(2).text();
            //     bookPackage = bookPackage.substring(bookPackage.indexOf("：") + 1);
            //     //ISBN号
            //     ISBN = keys.get(4).text();
            //     ISBN = ISBN.substring(ISBN.indexOf("：") + 1);
            //
            //     Elements select = bookDetailDesc.select("#detail").select("#catalog-show");
            //
            //     catalog = select.text();
            // }
            // 将数据封装到实体类
            BookInfo book = new BookInfo();
            book.setName(bookName);
            book.setImageUrl(imgUrl);
            book.setOutline(outline);
            book.setAuthor(author);
            book.setBookCategoryId(Integer.parseInt(category));
            String substring = discount.substring(
                    discount.indexOf("(") + 1, Math.max(discount.indexOf(")") - 1, 0));
            book.setDiscount(BigDecimal.valueOf(
                            Double.parseDouble(
                                    ObjectUtils.isEmpty(substring) ? "0" : substring
                            )
                    )
            );
            book.setPrice(BigDecimal.valueOf(Double.parseDouble(bookRobPrice)));
            book.setMarketPrice(BigDecimal.valueOf(Double.parseDouble(bookMarketPrice)));
            book.setPress(press);
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(publishDate);
            book.setPublishDate(date);
            book.setSize(bookSize);
            book.setPackStyle(bookPackage);
            book.setIsbn(ISBN);
            book.setCatalog(catalog);
            book.setDetail(detail);
            book.setStoreId(1);
            book.setStoreTime(new Date());
            book.setDealMount(0);
            book.setLookMount(0);
            book.setStoreMount(200);

            datas.add(book);
            if (i++ == 30) {
                break;
            }
        }
        return datas;
    }
}
